package com.zengqingfa.designpattern.create.prototype.deep;

import java.io.*;

/**
 *
 * @fileName: Shape
 * @author: zengqf3
 * @date: 2021-4-23 17:33
 * @description:
 */
public class Shape implements Cloneable, Serializable {

    private String name;

    private Owner owner;

    public Shape(String name, Owner owner) {
        this.name = name;
        this.owner = owner;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Owner getOwner() {
        return owner;
    }

    public void setOwner(Owner owner) {
        this.owner = owner;
    }

    //方式一：使用clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Shape clone = (Shape) super.clone();
        clone.owner = (Owner) clone.getOwner().clone();
        return clone;
    }

    @Override
    public String toString() {
        return "Shape{" + "name='" + name + '\'' + ", owner=" + owner + '}' + super.toString();
    }

    //方式二：序列化
    //注意：必须实现Serializable接口，否则会抛NotSerializableException异常
    protected Object deepClone() throws CloneNotSupportedException, IOException, ClassNotFoundException {
        //将对象写入流中
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bao);
        oos.writeObject(this);

        //将对象从流中取出
        ByteArrayInputStream bis = new ByteArrayInputStream(bao.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (ois.readObject());
    }
}
